package com.ruoyi.platform.utils;

import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @Author: ES
 * @Date: 2022/8/13 16:51
 * @Description: 处理根异常丢失的问题
 **/
public class RootExceptionUtil {

    public static String getExceptionMessage(Throwable e) {
        return getMessage(e);
    }

    public static String getRootCauseMessage(Throwable e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        root = root == null ? e : root;
        return getExceptionMessage(e);
    }

    public static String getMessage(Throwable th) {
        if (th == null) {
            return "";
        } else {
            String msg = extractMessageFromXML(th.getMessage());
            return StringUtils.defaultString(msg);
        }
    }

    public static String extractMessageFromXML(String message) {
        if (StringUtil.isEmpty(message)) {
            return StringUtils.defaultString(message);
        } else {
            try {
                Pattern regex = Pattern.compile("^.*?<CommonResult>.*?<message>(.*?)</message>.*?</CommonResult>.*?$");
                Matcher regexMatcher = regex.matcher(message);
                if (regexMatcher.matches()) {
                    return regexMatcher.group(1);
                }
            } catch (PatternSyntaxException var3) {
            }

            return message;
        }
    }

    public static Throwable getRootCause(Throwable throwable) {
        return ExceptionUtils.getRootCause(throwable);
    }

    public static String getFullStackTrace(Throwable throwable) {
        return ExceptionUtils.getRootCauseMessage(throwable);
    }
}
